package com.pphh.demo.consumer;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.rpc.RpcException;
import com.pphh.demo.DemoService;

/**
 * A example shows how to control the speed of dubbo rpc calls by QPS
 * this example make reference to sentinel's demo examples.
 * https://github.com/alibaba/Sentinel
 *
 * @author pphh
 * @date 2019/1/17
 */
public class ConsumerBootstrap {

    public static void main(String[] args) {
        ReferenceConfig<DemoService> reference = new ReferenceConfig<>();
        reference.setApplication(new ApplicationConfig("first-dubbo-consumer"));
        reference.setRegistry(new RegistryConfig("multicast://224.5.6.7:1234"));
        reference.setInterface(DemoService.class);
        reference.setVersion("1.0.0");
        DemoService greetingsService = reference.get();

        for (int i = 0; i < 15; i++) {
            try {
                String message = greetingsService.sayHello("michael");
                System.out.println("Success: " + message);
            } catch (RpcException ex) {
                if (ex.getCause().getMessage().contains("com.alibaba.csp.sentinel.slots.block.flow.FlowException")) {
                    System.out.println("Blocked by sentinel, QPS limit = 10, which is controlled on provider side");
                } else {
                    ex.printStackTrace();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
